package com.star.percalservice.service.impl;

import ch.qos.logback.core.util.StringUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.star.percalservice.mapper.TeacherMapper;
import com.star.percalservice.mapper.UserMapper;
import com.star.percalservice.model.dto.UserDTO;
import com.star.percalservice.model.entity.Teacher;
import com.star.percalservice.model.entity.User;
import com.star.percalservice.service.UserService;
import com.star.percalservice.utils.AesPasswordUtils;
import com.star.percalservice.utils.JwtTokenUtils;
import com.star.percalservice.utils.R;
import io.jsonwebtoken.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author star
 * @version 1.0
 * @Description:
 * @DateTime 2025/4/11 23:35
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AesPasswordUtils aesPasswordUtils;

    @Autowired
    private TeacherMapper teacherMapper;

    @Override
    public R login(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNull(user)) {
            return R.error("用户名或密码错误");
        }
        try {
            if (!aesPasswordUtils.comparePasswords(user.getPassword(), password)) {
                return R.error("用户名或密码错误");
            }
        } catch (Exception e) {
            return R.error("服务器错误:" + e.getMessage());
        }
        String token = JwtTokenUtils.generateToken(user.getId());
        user.setPassword(null);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", user);
        return R.ok("登录成功", map);
    }

    @Override
    public R register(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        if (ObjectUtil.isNotNull(userMapper.selectOne(queryWrapper))) {
            return R.error("用户名已存在");
        }
        try {
            user.setPassword(aesPasswordUtils.encryptPassword(user.getPassword()));
        } catch (Exception e) {
            return R.error("服务器错误:" + e.getMessage());
        }
        // 注册默认角色为teacher
        user.setRole("teacher");
        userMapper.insert(user);
        // 获取到用户id
        queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        user.setId(userMapper.selectOne(queryWrapper).getId());
        // 更新教师表
        Teacher teacher = new Teacher();
        teacher.setUserId(user.getId());
        // 默认计算机学院
        teacher.setDepartment("计算机科学与技术学院");
        // 默认讲师
        teacher.setTitle("讲师");
        return teacherMapper.insert(teacher) > 0 ? R.ok("注册成功") : R.error("注册失败");
    }

    @Override
    public R list(UserDTO.UserListDTO userListDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (Strings.hasLength(userListDTO.getUsername())) {
            queryWrapper.like("username", userListDTO.getUsername());
        }
        if (Strings.hasLength(userListDTO.getRealName())) {
            queryWrapper.like("real_name", userListDTO.getRealName());
        }
        if (Strings.hasLength(userListDTO.getRole())) {
            queryWrapper.eq("role", userListDTO.getRole());
        }
        return R.ok("查询成功", userMapper.selectList(queryWrapper));
    }

    @Override
    public R add(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        if (ObjectUtil.isNotNull(userMapper.selectOne(queryWrapper))) {
            return R.error("用户名已存在");
        }
        try {
            user.setPassword(aesPasswordUtils.encryptPassword(user.getPassword()));
        } catch (Exception e) {
            return R.error("服务器错误:" + e.getMessage());
        }
        userMapper.insert(user);
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        User resUser = userMapper.selectOne(queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("uid", resUser.getId());
        return R.ok("添加成功", map);
    }

    @Override
    public R update(User user) {
        User u = userMapper.selectById(user.getId());
        user.setPassword(u.getPassword());
        return userMapper.updateById(user) > 0 ? R.ok("修改成功") : R.error("修改失败");
    }

    @Override
    public R changePassword(Integer id, String password) {
        try {
            User user = userMapper.selectById(id);
            user.setPassword(aesPasswordUtils.encryptPassword(password));
            return userMapper.updateById(user) > 0 ? R.ok("修改成功") : R.error("修改失败");
        } catch (Exception e) {
            return R.error("服务器错误:" + e.getMessage());
        }
    }

}
